from .. import config as CONFIG
from .. import db
import os
from .configs import parse_tools, parse_versions

ConfigMap = {}

TOOL_CONFIG_NAME = "tools.cfg"
VERSION_CONFIG_NAME = "versions.cfg"


def tools_init(app):
    dir = CONFIG["default"].WATCHED_DIR
    # 直接对所有文件内容进行更新
    # 忽略在系统关闭期间的删除
    with app.app_context():
        for root, dirlist, filelist in os.walk(dir):
            if TOOL_CONFIG_NAME in filelist:
                result = parse_tools(os.path.join(root, TOOL_CONFIG_NAME))
                _commit_modified(result)
            if VERSION_CONFIG_NAME in filelist:
                result = parse_versions(os.path.join(root, VERSION_CONFIG_NAME))
                _commit_modified(result)


def parse_config(file_path, app):
    with app.app_context():
        file_name = os.path.basename(file_path)
        if file_name == VERSION_CONFIG_NAME:
            result = parse_versions(file_path)
        elif file_name == TOOL_CONFIG_NAME:
            result = parse_tools(file_path)
        else:
            result = ([], [])
        _commit_modified(result)


def _commit_modified(result):
    # 查询所有匹配项
    try:
        db.session.add_all(result[0])
        for i in result[1]:
            db.session.delete(i)
        db.session.commit()
    except Exception as e:
        print(str(e))
